package com.kuangstudy.service.collect;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kuangstudy.entity.Collect;
import com.kuangstudy.entity.CollectCategory;
import com.kuangstudy.mapper.CollectMapper;
import com.kuangstudy.service.collectcategory.ICollectCategoryService;
import com.kuangstudy.vo.CollectVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Description:
 * Author: yykk Administrator
 * Version: 1.0
 * Create Date Time: 2021/12/1 20:34.
 * Update Date Time:
 *
 * @see
 */
@Component("collectSqlAllService")
@Slf4j
public class CollectSqlAllServiceImpl extends ServiceImpl<CollectMapper, Collect> implements ICollectService {

    @Autowired
    private ICollectCategoryService collectCategoryService;

    @Override
    public List<CollectVo> loadCollectVos() {
        log.info("--------------> collectSqlAllService");
        // 1: 查询所有的分类
        List<CollectCategory> collectCategories = collectCategoryService.list();
        // 2： 查询表中所有的收藏夹的数据
        LambdaQueryWrapper<Collect> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Collect::getStatus, 1);
        // 3: 查询所有数据
        List<Collect> collectList = this.list(lambdaQueryWrapper);
        // 4: 根据分类进行分组
        Map<Integer, List<Collect>> collectMap = collectList.stream().collect(Collectors.groupingBy(s -> s.getCategoryId()));
        // 5: 根据分组的分类ID去收藏数据中进行查询
        List<CollectVo> collectVoList = new ArrayList<>();
        for (Map.Entry<Integer, List<Collect>> entry : collectMap.entrySet()) {
            CollectVo collectVo = new CollectVo();
            collectVo.setCategoryTitle(
                    collectCategories.stream()
                    .filter(s -> s.getId().equals(entry.getKey())).
                    findFirst().get()
                    .getCategoryTitle());
            collectVo.setCategoryId(entry.getKey());
            collectVo.setCollectList(entry.getValue());
            collectVoList.add(collectVo);
        }
        // 6: 返回即可
        return collectVoList;
    }



}


